from http.server import BaseHTTPRequestHandler
from cgi import parse_header, parse_multipart
from urllib.parse import parse_qs, urlparse, unquote, quote
import json

def parse_get(self):
	parsed_path = urlparse(self.path)
	try:
		data = dict([list([unquote(v) for v in p.split('=')]) for p in parsed_path[4].split('&')])
	except:
		data = {}
	return data

def parse_post(self):
	ctype, pdict = parse_header(self.headers['content-type'])
	data = {}
	length = int(self.headers['content-length'])
	if ctype == 'multipart/form-data':
		pdict['boundary'] = pdict['boundary'].encode()
		data = parse_multipart(self.rfile, pdict)
	elif ctype == 'application/x-www-form-urlencoded':
		for arg in quote(self.rfile.read(length).decode()).replace('%3D', '=').split('%26'):
			parsed_data = parse_qs(arg, keep_blank_values=1)
			data[list(parsed_data.keys())[0]] = list(parsed_data.values())[0]
		for k in data:
			data[k] = list([unquote(v) for v in data[k]])
	elif ctype == 'application/json':
		data = json.loads(self.rfile.read(length).decode())
	return data

def type_post(self):
	ctype, pdict = parse_header(self.headers['content-type'])
	if ctype == 'multipart/form-data':
		return 'formdata'
	elif ctype == 'application/x-www-form-urlencoded':
		return 'urlencode'
	elif ctype == 'application/json':
		return 'json'
	else:
		return 'unknown'
